package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存地理位置
    public void save(Long userId, Double latitude, Double longitude, String addrStr) {
        //查询
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if (exists){
            //存在  更新
            Update update = new Update();
            update.set("location",new GeoJsonPoint(latitude,longitude));
            update.set("address",addrStr);
            update.set("updated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,UserLocation.class);

        }else {
            //不存在 保存
            UserLocation location = new UserLocation();
            location.setAddress(addrStr);
            location.setUserId(userId);
            location.setCreated(System.currentTimeMillis());
            location.setLocation(new GeoJsonPoint(latitude,longitude));
            mongoTemplate.save(location);
        }
    }

//搜索附近
    public List<Long> searchNear(Long userId, String distance) {
          //查询当前用户坐标
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        //获取经纬度
        GeoJsonPoint point = location.getLocation();
        //创建半径
        Double miles = Double.valueOf(distance);
        Distance dis = new Distance(miles/1000, Metrics.KILOMETERS);
        //画圆
        Circle circle = new Circle(point, dis);
        //查
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //获取集合中的id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);


        return ids;
    }
}
